package com.call.service;

import com.call.Constants;
import com.call.R;
import com.call.activity.MainActivity;
import com.call.data.MissCallData;
import com.call.data.MissSMSData;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class SMSService extends Service{

	private final String TAG = "SMSService";
	private MissSMSData m_objSMSData;
	
	public static SMSService instance = null;
	
	//
	public static boolean isInstanceCreated() { 
	      return instance != null; 
	}//met

	
	
	private class ServiceBinder extends Binder implements ISMSService{
		

		public void DeleteSMSReceiverInfo(int id) {
			// TODO Auto-generated method stub
			m_objSMSData.delete(MissCallData.TableColumns._ID + " = "+id, null);
			Log.i(Constants.Tag, "delete sms: "+ id +" info from service");
		}

		public void AddSMSReceiverInfo(String phoneNumber, long time,
				String messageBody) {
			// TODO Auto-generated method stub
			
			addMissSMS(phoneNumber, time, messageBody);
			
		}

		public Cursor GetSMSReceiverInfo() {
			// TODO Auto-generated method stub
			Cursor res = m_objSMSData.query(null, null, null, MissCallData.TableColumns.CallTime + " DESC ", 0, Integer.MAX_VALUE);
			//Log.i(Constants.Tag, "get miss call info from service");
			return res;
			//return null;
		}
	}
	
	private void addMissSMS(String phoneNumber,long time, String messageBody)
	{
		//if (!isMissedCall(phoneNumber))
		//	return;
    	Log.v("DEBUG", "Missed Call: " + phoneNumber);

		NotificationManager notificationManager;
		Notification notification = null;
		PendingIntent pendingIntent;
		ContentValues values = new ContentValues();
		
		values.put(MissSMSData.TableColumns.SMSTime, time);
		values.put(MissSMSData.TableColumns.SMSNumber, phoneNumber);
		values.put(MissSMSData.TableColumns.SMSMessageBody, messageBody);

		m_objSMSData.insert(values);
		
		//Show message in the notify bar.
		notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		notification = new Notification();
        
		Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(Intent.ACTION_VIEW);
        notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		notification.icon = R.drawable.attention;  
		notification.defaults = Notification.DEFAULT_SOUND;
		
		//Click it and it will disappear
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.setLatestEventInfo(this, "Missed SMS", phoneNumber, pendingIntent);
		notification.tickerText = "Missed SMS from " + phoneNumber;
		notificationManager.notify(Constants.notificationID, notification);
	}
	
	public ServiceBinder serviceBind = new ServiceBinder();
	private SMSListener mSMSListener;
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		//initialize service
		
		Log.v(TAG, "onCreate ");
		
		m_objSMSData = MissSMSData.GetMissSMSData(this, Constants.MISSSMS_TABLENAME);
		
		//mSMSListener = new SMSListener(serviceBind);
		
		IntentFilter filter = new IntentFilter();
        mSMSListener = new SMSListener(serviceBind);
        registerReceiver(mSMSListener, filter);
        
        //Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
       // IntentFilter filter = new IntentFilter(SMS_RECEIVED);       
       // registerReceiver(SMSReceiver, filter);
		//re
		//initialize service

		
		// register phone dial state listener.
		//TelephonyManager mTelephonyManager;
       // mTelephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       // mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        //Log.i(Constants.Tag, "Add Miss call and phone number service.\n");
		instance = this;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return serviceBind;
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mSMSListener);
		instance = null;
	}
	

	/*final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	
	BroadcastReceiver SMSReceiver = new BroadcastReceiver()
	{
		
		protected String className = this.getClass().getName();
		protected int toastLength = Toast.LENGTH_SHORT;    
	
	    @Override
	    public void onReceive(Context context, Intent intent) {
	        Toast.makeText(context, className, toastLength).show();
	        Log.i("INCOMINGSMSRECEIVER", intent.getAction());
	
	        if (intent.getAction().equals(SMS_RECEIVED)) {
	            SmsManager sms = SmsManager.getDefault();
	
	            Bundle bundle = intent.getExtras();
	            if (bundle != null) {
	                Object[] pdus = (Object[]) bundle.get("pdus");
	                SmsMessage[] messages = new SmsMessage[pdus.length];
	                for (int i=0; i<pdus.length; i++)
	                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
	
	                for (SmsMessage message : messages) {
	                	long now = System.currentTimeMillis();
	                    String msg = message.getMessageBody();
	                    String to = message.getOriginatingAddress();
	                    //sms.sendTextMessage(to, null, "Got It" + msg, null, null);
	                    Log.i("INCOMINGSMSRECEIVER", "SMS received."); 
	                    //m_objSMSData.
	                    serviceBind.AddSMSReceiverInfo(to, now, msg);
	                }
	            }
	        	}           
	    	}
	}; */

}
